<template>
  <div class="employee_create">
    <div class="employee_create_form Row_content">
      <Form ref="formValidate"
            :model="formValidate"
            :rules="ruleValidate"
            :label-width="80"
            style="width:600px;margin:auto">
        <FormItem label="手机号码:"
                  prop="phoneNumber">
          <Input v-model="formValidate.phoneNumber"
                 placeholder="请输入手机号"
                 @on-keyup="allowNumber"
                 style="width:280px"
                 :maxlength="11"></Input>
        </FormItem>
        <FormItem label="姓名:"
                  prop="username">
          <Input v-model="formValidate.username"
                 placeholder="请输入姓名"
                 @on-keyup="filterSpace"
                 :maxlength="20"></Input>
        </FormItem>
        <FormItem label="性别"
                  prop="sex">
          <RadioGroup v-model="formValidate.sex"
                      @on-change="sex_change"
                      v-if='loaded'>
            <Radio label="1"
                   style="margin-right:30px">男</Radio>
            <Radio label="0">女</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem label="邮箱地址:"
                  prop="email">
          <Input v-model="formValidate.email"
                 placeholder="请输入邮箱地址"
                 @on-keyup="filterSpaceEmail"
                 :maxlength="40"></Input>
        </FormItem>
        <FormItem label="组织机构"
                  prop="orgId">
          <treeselect v-model='formValidate.orgId'
                      :options="options"
                      noResultsText="未搜索符合的组织机构"
                      noOptionsText="组织机构为空"
                      :normalizer="normalizer"
                      @select="selectList"
                      placeholder="请选择组织" />
        </FormItem>
        <FormItem label="角色"
                  prop="roleIdList">
          <Select v-model="formValidate.roleIdList"
                  multiple
                  filterable
                  style="width:280px"
                  :class="{'ivu-select-width': formValidate.roleIdList.length > 0}"
                  @on-change="roleIdList_change">
            <Option v-for="item in roleIdList"
                    :value="item.value"
                    :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem class="form-btn">
          <Button type="primary"
                  class="system-submit-btn"
                  :disabled="isDisabled"
                  @click="handleSubmit('formValidate')">确定</Button>
          <Button @click="handleReset('formValidate')"
                  style="margin-left: 8px"
                  class="system-submit-btn">取消</Button>
        </FormItem>
      </Form>
    </div>
  </div>
</template>
<script>
import { routeEqual } from '@/libs/util'
import { checkPhone } from '@/libs/validate'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { setEmployeeCreate, setEmployeeUpdate, getEmployeeTree, getRoleList, getUserInfos } from '@/api/system/employee.js'
export default {
  name: 'employee_create',
  components: { Treeselect },
  data () {
    return {
      loaded: false,
      userId: '', // 判断是编辑还是新增还是详情
      flag: true,
      roleIdList: [],
      isDisabled: false,
      formValidate: {
        merchantId: this.$store.state.user.merchantId,
        phoneNumber: '', // 手机号码
        username: '', // 姓名
        sex: '1', // 性别
        email: '', // 邮箱
        orgId: null, // 组织机构
        roleIdList: []// 角色
      },
      ruleValidate: {
        phoneNumber: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ],
        username: [
          { required: true, message: '姓名不能为空', trigger: 'blur' },
          {
            required: true,
            validator: (rule, value, callback) => {
              let rea = /^[\u4e00-\u9fa5]{1,20}$/
              if (rea.test(value)) {
                callback()
              } else {
                callback(new Error('只允许输入汉字'))
              }
            },
            trigger: 'blur'
          }
        ],
        sex: [
          {}
        ],
        email: [
          {
            validator: (rule, value, callback) => {
              let myReg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/
              // let myReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
              // let myReg = /^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$/
              if (myReg.test(value)) {
                callback()
              } else if (!value) {
                callback()
              } else {
                callback(new Error('邮箱格式不正确'))
              }
            },
            trigger: 'blur'
          }
        ],
        orgId: {
          required: true,
          message: '组织机构不能为空'
          // validator: (rule, value, callback) => {
          //   if (value === null) {
          //     callback(new Error('组织机构不能为空'))
          //   } else {
          //     callback()
          //   }
          // }
        },
        roleIdList: [
          { required: true, message: '角色不能为空', trigger: 'change', type: 'array' },
          {
            validator: (rule, value, callback) => {
              if (value.length >= 7) {
                callback(new Error('最多选择6个角色'))
              } else {
                callback()
              }
            }
          }
        ]
      },
      options: [
      ],
      normalizer (node) {
        let aa
        if (Object.prototype.toString.call(node.childList) === '[object Array]') {
          if (!node.childList.length) {
            aa = undefined
          } else {
            aa = node.childList
          }
        } else {
          aa = undefined
        }
        return {
          id: node.id,
          label: node.orgName,
          children: aa
        }
      }
    }
  },
  created () {
  },
  mounted () {
    this.userId = this.$route.params.id
    if (this.userId) {
      this.router()
    } else {
      this.loaded = true
    }
    this.getOrgTree()
    this.getRoleAll()
  },
  watch: {
  },
  methods: {
    filterSpace () {
      this.formValidate.username = this.formValidate.username.replace(/\s+/g, '')
    },
    filterSpaceEmail (e) {
      e.target.value = e.target.value.replace(/\s+/g, '').replace(/[\u4E00-\u9FA5]/g, '')
      this.formValidate.email = e.target.value
    },
    allowNumber () {
      this.formValidate.phoneNumber = this.formValidate.phoneNumber.replace(/[^0-9]+/g, '')
    },
    selectList (data) { // 选择组织机构树
      this.formValidate.orgId = data.id
      this.$refs.formValidate.validate((valid) => { })
    },
    getOrgTree () { // 获取组织机构树
      getEmployeeTree({
        'merchantId': this.$store.state.user.merchantId, status: 1
      }).then((res) => {
        if (res.data.status === 200) {
          this.options.push(res.data.data)
        } else {
          this.$Message.error(`${res.data.error}`)
        }
      })
    },
    getRoleAll () { // 获取角色
      getRoleList({
        'merchantId': this.$store.state.user.merchantId,
        'status': 1
      }).then((res) => {
        if (res.data.status === 200) {
          res.data.data.forEach(ele => {
            this.$set(ele, 'label', ele.roleName)
            this.$set(ele, 'value', ele.id)
          })
          this.roleIdList = res.data.data
        } else {
          this.$Message.error(`${res.data.message}`)
        }
      })
    },
    sex_change (sta) { // 选择性别
      this.formValidate.sex = sta
    },
    roleIdList_change (arr) { // 选择角色 获取roleIdList
      if (arr.length < 7) {
        this.formValidate.roleIdList = arr
      } else {
        this.formValidate.roleIdList = arr.slice(0, 6)
        this.$Message.error('最多只能选择6个角色')
      }
    },
    router () {
      getUserInfos({// 详情和编辑过来调用查找数据
        'id': this.userId
      }).then((res) => {
        if (res.data.status === 200) {
          this.loaded = true
          this.formValidate.roleIdList = []
          this.formValidate.phoneNumber = res.data.data.phoneNumber
          this.formValidate.username = res.data.data.username
          this.formValidate.sex = res.data.data.sex + ''
          this.formValidate.email = res.data.data.email
          this.formValidate.orgId = res.data.data.orgId
          res.data.data.roleList.forEach((ele) => {
            this.formValidate.roleIdList.push(ele.id)
          })
        } else {
          this.loaded = true
          this.$Message.error(`${res.data.message}`)
        }
      })
    },
    closeModal () {
      this.$store.commit('closeTag', this.$route)
      this.$store.commit('setTagNavList', this.$store.state.app.tagNavList.filter(item => !routeEqual(this.$route, item)))
      this.$nextTick(() => {
        this.$router.push({
          name: 'employee_list'
        })
      })
    },
    handleSubmit (name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (!this.isDisabled) {
            if (this.isDisabled) {
              return
            }
            if (!this.userId) { // 存在即调用新增创建
              setEmployeeCreate(
                { ...this.formValidate }
              ).then((res) => {
                setTimeout(() => {
                  this.isDisabled = false
                }, 500)
                if (res.data.status === 200) {
                  this.$Message.success('新增成功')
                  this.closeModal()
                } else {
                  this.$Message.error(`${res.data.message}`)
                }
              })
            } else { // 不存在即调用编辑
              setEmployeeUpdate({
                ...this.formValidate, 'id': this.userId
              }).then((res) => {
                setTimeout(() => {
                  this.isDisabled = false
                }, 500)
                if (res.data.status === 200) {
                  this.$Message.success('编辑成功')
                  this.closeModal()
                } else {
                  this.$Message.error(`${res.data.message}`)
                }
              })
            }
          }
        }
      })
    },
    handleReset (name) {
      this.$refs[name].resetFields()
      this.closeModal()
    }
  }
}
</script>
<style>
.employee_create .ivu-select-width .ivu-select-input {
  width: 100px !important;
}
</style>
